package com.dongpl.module.sysInfo.util;

import com.dongpl.module.sysInfo.vo.*;
import com.dongpl.utils.Arith;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.NetworkParams;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * 服务器信息类
 */
public class Server {

    // 线程等待时间
    private static final int WAIT_SECOND = 1000;
    // 格式化浮点型数据
    private static final DecimalFormat df = new DecimalFormat("0.00");
    // 格式化时间数据
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * CPU相关信息
     */
    private static Cpu cpu = new Cpu();

    /**
     * 內存相关信息
     */
    private static Mem mem = new Mem();

    /**
     * JVM相关信息
     */
    private static Jvm jvm = new Jvm();

    /**
     * 服务器相关信息
     */
    private static Sys sys = new Sys();

    /**
     * 磁盘相关信息
     */
    private static List<SysFile> sysFiles = new LinkedList<>();

    public Cpu getCpu() {
        return cpu;
    }

    public void setCpu(Cpu cpu) {
        Server.cpu = cpu;
    }

    public Mem getMem() {
        return mem;
    }

    public void setMem(Mem mem) {
        Server.mem = mem;
    }

    public Jvm getJvm() {
        return jvm;
    }

    public void setJvm(Jvm jvm) {
        Server.jvm = jvm;
    }

    public Sys getSys() {
        return sys;
    }

    public void setSys(Sys sys) {
        Server.sys = sys;
    }

    public List<SysFile> getSysFiles() {
        return sysFiles;
    }

    public void setSysFiles(List<SysFile> sysFiles) {
        Server.sysFiles = sysFiles;
    }

    public static Server getMSG(){
        Server server = new Server();
        SystemInfo sysInfo = new SystemInfo();
        HardwareAbstractionLayer hal = sysInfo.getHardware();
        CentralProcessor processor = hal.getProcessor();
        OperatingSystem os = sysInfo.getOperatingSystem();
        //存入cpu
        server.setCpu(setCpuInfo(processor));
        //内存
        server.setMem(setMemInfo(hal.getMemory()));
        //系统信息
        server.setSys(setSysInfo(os));
        //jvm信息
        server.setJvm(setJvmInfo());
        //系统文件
        server.setSysFiles(setSysFiles(sysInfo.getOperatingSystem()));
        return server;
    }

    /**
     * 设置CPU信息
     */
    private static Cpu setCpuInfo(CentralProcessor processor) {
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softIrq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long ioWait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + ioWait + irq + softIrq + steal;
        cpu.setCpuNum(processor.getLogicalProcessorCount() + "个");
        cpu.setSys(df.format(cSys * 100d / totalCpu) + "%");
        cpu.setUsed(df.format(user * 100d / totalCpu) + "%");
        cpu.setFree(df.format(idle * 100d / totalCpu) + "%");
        return cpu;
    }

    /**
     * 设置内存信息
     */
    private static Mem setMemInfo(GlobalMemory memory) {
        mem.setTotal(convertFileSize(memory.getTotal()));
        mem.setUsed(convertFileSize(memory.getTotal() - memory.getAvailable()));
        mem.setFree(convertFileSize(memory.getAvailable()));
        return mem;
    }

    /**
     * 设置服务器信息
     */
    private static Sys setSysInfo(OperatingSystem os) {
        Properties props = System.getProperties();
        NetworkParams networkParams = os.getNetworkParams();
        sys.setComputerName(networkParams.getHostName());
        sys.setComputerIp(networkParams.getIpv4DefaultGateway());
        sys.setOsName(String.valueOf(os));
        sys.setOsArch(props.getProperty("os.arch"));
        sys.setUserDir(props.getProperty("user.dir"));
        return sys;
    }

    /**
     * 设置Java虚拟机
     */
    private static Jvm setJvmInfo() {
        Properties props = System.getProperties();
        Runtime runtime = Runtime.getRuntime();
        jvm.setTotal(convertFileSize(runtime.totalMemory()));
        jvm.setMax(convertFileSize(runtime.maxMemory()));
        jvm.setFree(convertFileSize(runtime.freeMemory()));
        jvm.setName("Java");
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setStartTime(sdf.format(new Date()));
        jvm.setRunTime("520分钟");
        jvm.setHome(props.getProperty("java.home"));
        return jvm;
    }

    /**
     * 设置磁盘信息
     */
    private static List<SysFile> setSysFiles(OperatingSystem os) {
        FileSystem fileSystem = os.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        sysFiles.clear();
        for (OSFileStore fs : fsArray) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            SysFile sysFile = new SysFile();
            sysFile.setDirName(fs.getMount());
            sysFile.setSysTypeName(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(convertFileSize(total));
            sysFile.setFree(convertFileSize(free));
            sysFile.setUsed(convertFileSize(used));
            double use = Double.longBitsToDouble(used);
            double totaled = Double.longBitsToDouble(total);
            double div = Arith.div(use, totaled, 4);
            sysFile.setUsage(String.valueOf(Arith.mul(div, 100)));
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    /**
     * 字节转换
     * @param size 字节大小
     * @return 转换后值
     */
    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }


}
